package xin.marcher.module.search.repository;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import xin.marcher.module.search.domain.entity.ProductSearchDO;
import xin.marcher.module.search.mapper.SkuInfoMapper;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Repository
public class ProductSearchRepository {

    private static final String SKU_INFO_INDEX = "sku_info_index";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    /**
     * 根据skuId查询和商品索引相关的信息
     */
    public ProductSearchDO queryProductSearchInfo(String skuId) {
        return skuInfoMapper.queryProductSearchInfo(skuId);
    }

    /**
     * 根据itemId查询和商品索引相关的信息
     */
    public List<ProductSearchDO> queryProductSearchInfos(String itemId) {
        return skuInfoMapper.queryProductSearchInfos(itemId);
    }

    /**
     * 批量保存商品索引数据
     */
    public void saveProductSearchInfos(List<ProductSearchDO> productSearchDOS) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (ProductSearchDO productSearchDO : productSearchDOS) {
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("skuName", productSearchDO.getSkuName());
            jsonMap.put("basePrice", productSearchDO.getBasePrice());
            jsonMap.put("vipPrice", productSearchDO.getVipPrice());
            jsonMap.put("brandId", productSearchDO.getBrandId());
            jsonMap.put("brandName", productSearchDO.getBrandName());
            jsonMap.put("createTime", new Date());
            jsonMap.put("updateTime", new Date());
            IndexRequest indexRequest = new IndexRequest(SKU_INFO_INDEX).id(productSearchDO.getSkuId()).source(jsonMap);
            bulkRequest.add(indexRequest);
        }
        restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
